package com.android.manghe.market.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.PagerAdapter
import com.android.base.frame.extend.IRefresh
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPFragment
import com.android.base.tools.DisplayUtil
import com.android.base.tools.Glide.GlideHelper
import com.android.manghe.R
import com.android.manghe.cache.ConfigHolder
import com.android.manghe.cache.UserHolder
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.market.activity.CartActivity
import com.android.manghe.market.activity.MarketGoodDetailActivity
import com.android.manghe.market.model.MarketCommentRes
import com.android.manghe.market.model.MarketGoodDetailRes
import com.android.manghe.market.model.Product
import com.android.manghe.market.presenter.PMarketGoodDetail
import com.android.manghe.market.view.sku.ProductSkuDialog
import com.android.manghe.orderpay.activity.MarketOrderPayActivity
import com.android.manghe.orderpay.activity.NoPriceMarketOrderPayActivity
import com.android.manghe.user.activity.LoginActivity
import com.android.manghe.utils.AnalyzeUtil
import com.android.manghe.view.MyScrollView
import com.android.manghe.zhuli.activity.WebTextActivity
import com.meiqia.meiqiasdk.util.MQIntentBuilder
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.squareup.picasso.Picasso
import com.tmall.ultraviewpager.UltraViewPager
import kotlinx.android.synthetic.main.fragment_market_good_detail.*
import java.text.DecimalFormat
import java.util.*

class MarketDetailFragment : MVPFragment<PMarketGoodDetail>(), IRefresh {

    var mPicHeight = 0
    private var showSkuDialogTarget = 0 //0内容视图选择，1加入购物车，2立即购买
    private var dialog: ProductSkuDialog? = null

    override fun getRefreshView(): SmartRefreshLayout {
        return mView.findViewById(R.id.refreshLayout)
    }

    override fun onRefresh() {
        p.loadData()
        val config = ConfigHolder.getConfigInfo(activity)
        if (config != null && config.comment_switch == 1) {
            p.loadComment()
        }
    }

    override fun showToolBarType(): ETitleType {
        return ETitleType.NO_TITLE
    }

    override fun initData(savedInstanceState: Bundle?, parent: View?) {
        mPicHeight = DisplayUtil.dip2px(activity, 360f)

        p.setGoodId(arguments!!.getString("goodId"))
        onRefresh()
        p.getMemberInfo()

        val config = ConfigHolder.getConfigInfo(activity)
        if (config != null) {
            tvRule.visibility = if(config.exempt_rule_switch == 1) View.VISIBLE else View.GONE
            tvRule.setOnClickListener {
                AnalyzeUtil.clickRule(activity!!, 1)
                WebTextActivity.showActivity(activity!!, "商品助力规则", ConstantsUrl.domain + ConstantsUrl.ZHULI_RULE)
            }
            if(config.comment_switch == 0){
                layoutComment.visibility = View.GONE
            }
        }

        tvService.setOnClickListener {
            if(p.detail == null)
                return@setOnClickListener
            val userInfo = UserHolder.getUserInfo(activity)
            userInfo?.let {
                val clientInfo = HashMap<String, String>()
                clientInfo["mid"] = it.UID
                clientInfo["nickName"] = it.nickname ?: "未知"
                clientInfo["avatar"] = it.avatar
                startActivity(
                    MQIntentBuilder(activity)
                        .setClientInfo(clientInfo) // 设置顾客信息 PS: 这个接口只会生效一次,如果需要更新顾客信息,需要调用更新接口
                        .build()
                )
            }?:open(LoginActivity::class.java)
        }

        tvOriginalBuy.setOnClickListener {
            if(p.detail == null)
                return@setOnClickListener
            showSkuDialogTarget = 2
            showSkuDialog(true)
        }

        layoutMainDan.setOnClickListener {
            if(p.detail == null)
                return@setOnClickListener
            showSkuDialogTarget = 2
            showSkuDialog(false)
        }
        tvAddToCart.setOnClickListener {
            if(p.detail == null)
                return@setOnClickListener
            showSkuDialogTarget = 1
            showSkuDialog(false)
        }

        layoutSpec.setOnClickListener {
            if(p.detail == null)
                return@setOnClickListener
            showSkuDialogTarget = 0
            showSkuDialog(false)
        }

        tvCart.setOnClickListener {
            if(p.detail == null)
                return@setOnClickListener
            //购物车
            val userInfo = UserHolder.getUserInfo(activity)
            if (userInfo == null) {
                open(LoginActivity::class.java)
                return@setOnClickListener
            }
            open(CartActivity::class.java)
        }

        scrollView.setOnScrollListener(scrollerListener)
    }


    /**
     * isOriginalBuy true元
     */
    private fun showSkuDialog(isOriginalBuy: Boolean) {
        dialog = ProductSkuDialog(context!!)
        dialog!!.setData(Product.get(p.detail)) { sku, quantity ->
            // 数量 quantity
            if (!sku.id.isNullOrEmpty()) {
                // 设置已选字符
                var specArrName = ""
                if (!sku.attributes.isNullOrEmpty()) {
                    for (skuAttr in sku.attributes) {
                        specArrName += "${skuAttr.value} "
                    }
                    tvSelectedSpecName.text =
                        if (specArrName.isNotEmpty()) specArrName else "请选择"
                    if (showSkuDialogTarget == 0 || showSkuDialogTarget == 2) {
                        //点击商品内容中的选择分类，点击立即购买
                        //跳转到确认订单界面结算
                        if(isOriginalBuy){
                            open(
                                    MarketOrderPayActivity::class.java,
                                    hashMapOf<String, Any>(
                                            "goodId" to p.goodId,
                                            "qty" to quantity,
                                            "spec" to sku.id,
                                            "isMember" to p.isMember
                                    )
                            )
                        }else {
                            open(
                                NoPriceMarketOrderPayActivity::class.java,
                                hashMapOf<String, Any>(
                                    "goodId" to p.goodId,
                                    "qty" to quantity,
                                    "spec" to sku.id,
                                    "perPrice" to p.detail.price
                                )
                            )
                        }
                    } else {
                        p.addToCard(sku.id, quantity)
                    }
                }
            }
        }
        dialog?.show()
    }

    private var scrollerListener: MyScrollView.OnScrollListener? = null
    fun setScrollListener(listener: MyScrollView.OnScrollListener) {
        scrollerListener = listener
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_market_good_detail
    }

    override fun onLoad() {
    }

    @SuppressLint("SetTextI18n")
    fun updateView(detail: MarketGoodDetailRes.DataBean) {
        detail.thumbs?.let {
            ultraViewPager.adapter =
                GoodThumbViewPager(activity!!.applicationContext, it)
            if (it.size > 1) {
                ultraViewPager.initIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.backgroundGray))
                    .setRadius(DisplayUtil.dip2px(mContext, 6f))
                    .setMargin(0, 0, 0, DisplayUtil.dip2px(mContext, 10f))
                    .setGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM)
                    .build()
                ultraViewPager.setInfiniteLoop(true)
                ultraViewPager.setAutoScroll(5000)
            } else {
                ultraViewPager.disableIndicator()
                ultraViewPager.setInfiniteLoop(false)
            }
        }
        tvTitle.text = detail.name
        tvSaleAmount.text = "累计已售${detail.sell}件"
        tvAddScore.visibility = if(TextUtils.equals("0", detail.score)) View.GONE else View.VISIBLE
        tvScore.visibility = if(TextUtils.equals("0", detail.score)) View.GONE else View.VISIBLE
        tvScore.text = "${detail.score}积分"

        //价格
        val priceSplit = detail.price.split(".")
        if (priceSplit.size == 2) {
            tvPriceLeft.text = "￥${priceSplit[0]}"
            tvPriceRight.text = ".${priceSplit[1]}"
        }
        val df = DecimalFormat("#.00")
        tvBlackGoldPrice.text = df.format(detail.price.toFloat() * 0.95).toString()
        tvZengScore.text = "${detail.favourable_score}"

        showWeb(detail.content)
    }

    private fun showWeb(htmlString: String?) {
        if (htmlString.isNullOrEmpty()) {
            tvNoDetail.visibility = View.VISIBLE
            return
        }
        val picUrlList = p.htmlConvertPicList(htmlString)
        val lp = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        if(!picUrlList.isNullOrEmpty()){
            layoutDetailPics.removeAllViews()
            picUrlList.forEach {
                val iv = ImageView(activity)
//                iv.scaleType = ImageView.ScaleType.FIT_XY
                iv.adjustViewBounds = true
                iv.layoutParams = lp
                layoutDetailPics.addView(iv)


                // 显示图片
                Picasso.get().load(it)
                    .fit()
                    .into(iv)

                GlideHelper.load(activity, it, iv)
            }
        }


//        val js = "<style>\n" +
//                "body{\n" +
//                " max-width:80px;\n" +
//                "height:auto\n" +
//                "}\n" +
//                "</style>" + htmlString
//        webView.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
//        webView.settings.loadWithOverviewMode = true
//        webView.loadDataWithBaseURL(null, js, "text/html", "utf-8", null)
    }

    fun updateExemptAmount(){
        tvCanUse.text = "余额:${if(p.canUseEdu == 0.0) "0" else p.canUseEdu}元"
    }

    @SuppressLint("SetTextI18n")
    fun showComment(comment: MarketCommentRes.DataBean.ListBean, totalNum: Int) {
        try {
            layoutComment.visibility = View.VISIBLE
            tvCommentTitle.text = "评论（$totalNum）"
            GlideHelper.load(activity, comment.photo, ivCommentAvatar)
            tvCommentName.text = comment.nickname
            commentRatingBar.rating = comment.star.toFloat()
            tvCommentContent.text = comment.content
            tvCommentTitle.setOnClickListener {
                (activity as MarketGoodDetailActivity).showComment()
            }
        } catch (e: Exception) {
            layoutComment.visibility = View.GONE
        }

    }
}

class GoodThumbViewPager(
    context: Context,
    thumbList: List<MarketGoodDetailRes.DataBean.ThumbsBean>
) : PagerAdapter() {

    private var thumbList: List<MarketGoodDetailRes.DataBean.ThumbsBean>? = null
    private var context: Context? = null

    init {
        this.context = context
        this.thumbList = thumbList
    }

    override fun getCount(): Int {
        return thumbList!!.size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object`
    }

    @SuppressLint("InflateParams")
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val imageView = LayoutInflater.from(container.context)
            .inflate(R.layout.layout_pager_iv_item, null) as ImageView
        imageView.scaleType = ImageView.ScaleType.FIT_XY
        GlideHelper.load(context, thumbList!![position].src, imageView)
        container.addView(imageView)
        imageView.setOnClickListener {

        }
        return imageView
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        val view = `object` as ImageView
        container.removeView(view)
    }

}